import { ref, computed } from 'vue';
import { ElMessage } from 'element-plus';

const NODE_WIDTH = 120;
const NODE_HEIGHT = 80;

export function useWorkflowCanvas(workflow) {
    // 响应式状态
    const selectedNode = ref(null);
    const zoomLevel = ref(1);

    // 计算属性
    const nodeWidth = computed(() => NODE_WIDTH);
    const nodeHeight = computed(() => NODE_HEIGHT);

    // 方法
    const selectNode = (node) => {
        selectedNode.value = node;
    };

    const unselectNode = () => {
        selectedNode.value = null;
    }

    const zoomIn = () => {
        zoomLevel.value = Math.min(zoomLevel.value + 0.1, 2); // 限制最大缩放为200%
    };

    const zoomOut = () => {
        zoomLevel.value = Math.max(zoomLevel.value - 0.1, 0.5); // 限制最小缩放为50%
    };

    const resetZoom = () => {
        zoomLevel.value = 1;
    };

    const saveNodeConfig = () => {
        if (selectedNode.value) {
            // 在这里可以添加调用API保存节点配置的逻辑
            // workflowApi.updateNode(selectedNode.value.id, selectedNode.value.config)
            ElMessage.success('节点配置已保存');
            unselectNode();
        }
    };
    
    const getNodeIcon = (type) => {
        const icons = {
            trigger: '⚡️',
            condition: '💎',
            action: '🚀',
            delay: '⏳',
            end: '🏁'
        };
        return icons[type] || '📦';
    };

    const getConnectionPath = (connection) => {
        if (!workflow.value || !workflow.value.nodes) return '';
        
        const fromNode = workflow.value.nodes.find(n => n.id === connection.from);
        const toNode = workflow.value.nodes.find(n => n.id === connection.to);

        if (!fromNode || !toNode) return '';

        const startX = fromNode.x + nodeWidth.value / 2;
        const startY = fromNode.y + nodeHeight.value;
        const endX = toNode.x + nodeWidth.value / 2;
        const endY = toNode.y;

        // 使用简单的曲线路径
        const cp1X = startX;
        const cp1Y = startY + 50;
        const cp2X = endX;
        const cp2Y = endY - 50;

        return `M ${startX},${startY} C ${cp1X},${cp1Y} ${cp2X},${cp2Y} ${endX},${endY}`;
    };

    return {
        selectedNode,
        zoomLevel,
        nodeWidth,
        nodeHeight,
        selectNode,
        unselectNode,
        zoomIn,
        zoomOut,
        resetZoom,
        saveNodeConfig,
        getNodeIcon,
        getConnectionPath
    };
} 